package com.antcom.antread.antreaddatacrawl.himalayaData.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.antcom.antread.antreaddatacrawl.himalayaData.dto.VipUrlDto;
import com.antcom.antread.antreaddatacrawl.himalayaData.utils.vipEAD.VipEncryption;
import com.antcom.antread.antreaddatacrawl.util.SendRequestUtil;
import com.antcom.antread.antreaddatacrawl.himalayaData.entity.BookInfo;
import com.antcom.antread.antreaddatacrawl.himalayaData.entity.ChapterInfo;
import com.antcom.antread.common.core.baseRest.domain.PageDevice;
import com.antcom.antread.common.core.text.PropertiesUtil;
import com.antcom.antread.common.core.text.UUIDUtil;
import com.antcom.antread.common.core.utils.encryptUtil.URLUtil;
import com.antcom.antread.common.core.utils.string.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * himalaya 发送请求
 *
 * @Author 中国蚂蚁技术有限公司
 * @create 2020/12/5 9:40
 */
public class SendRequest {

    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger(SendRequest.class);

    /**
     * 总路径
     */
    private static String homeUrl = PropertiesUtil.getDocking("URL");

    /**
     * 下载书籍
     * @param param 书名
     * @param condition 标识
     * @param page 分页
     * @return
     */
    public static List<BookInfo> searchBOOK(String param,String condition,String page) {
        List<BookInfo> bookInfos = new ArrayList<>();
        String urlParam = URLUtil.URLEn(param);
        StringBuilder url = new StringBuilder();
        url.append(homeUrl);
        url.append(urlParam);
        url.append("&page=");
        url.append(page);
        url.append("&spellchecker=true&rows=20&condition=relation&device=iPhone&fq=&paidFilter=false");

        String responseParam = SendRequestUtil.sendHttpClientGET(url.toString());
        if (StringUtils.isEmpty(responseParam)) {
            return null;
        }
        JSONObject parseObject = JSONObject.parseObject(responseParam);
        JSONObject data = parseObject.getJSONObject("data");
        JSONObject album = data.getJSONObject("album");
        JSONArray docs = album.getJSONArray("docs");

        for (int i = 0; i < docs.size(); i++) {
            JSONObject docsObject = docs.getJSONObject(i);

            String nickname = docsObject.getString("nickname");
            System.out.println(nickname);
            // 输入下载条件 作者
            if(!condition.equals(nickname)){
                continue;
            }
            // 主键
            String uuid = UUIDUtil.getUUID();

            // 书籍id
            String albumId = docsObject.getString("albumId");

            // 书名
            String title = docsObject.getString("title");

            // 图片路径
            String coverPath = docsObject.getString("coverPath");


            // 书籍类型
            String categoryTitle = docsObject.getString("categoryTitle");

            // 描述
            String intro = docsObject.getString("intro");

            // 书籍id
            String docsUrl = docsObject.getString("url");

            BookInfo bookInfo = new BookInfo();
            bookInfo.setBookId(uuid);
            bookInfo.setBookName(title.trim());
            bookInfo.setBookPicture(coverPath);
            bookInfo.setBookAuthor(nickname);
            bookInfo.setBookDescription(intro);
            bookInfo.setBookTag(categoryTitle);
            bookInfo.setHimalayaId(albumId);
            bookInfo.setBookUrl(docsUrl);
            bookInfo.setCreateTime(new Date());
            bookInfos.add(bookInfo);
        }
        return bookInfos;
    }

    /**
     * 获取分页
     *
     * @param album 书籍id
     * @return PageDevice
     */
    private static PageDevice getPage(String album) {
        StringBuilder url = new StringBuilder();
        String pageUrl = PropertiesUtil.getDocking("GET_PAGE_URL");
        url.append(pageUrl);
        url.append(album);
        String responseParam = SendRequestUtil.sendHttpClientGET(url.toString());
        logger.info("分页信息返回参数:[{}]", url.toString());
        if (StringUtils.isEmpty(responseParam)) {
            return null;
        }
        JSONObject parseObject = JSONObject.parseObject(responseParam);
        JSONObject data = parseObject.getJSONObject("data");
        JSONObject tracksInfo = data.getJSONObject("tracksInfo");
        String totalCount = tracksInfo.getString("trackTotalCount");
        String pageSize = tracksInfo.getString("pageSize");
        PageDevice pageDevice = new PageDevice(totalCount, pageSize);
        return pageDevice;
    }

    /**
     * 下载章节信息
     *
     * @param album 书籍id
     * @return ChapterInfo
     */
    public static List<ChapterInfo> searchChapter(String album) {
        List<ChapterInfo> list = new ArrayList<>();
        String chapterUrl = PropertiesUtil.getDocking("GET_CHAPTER_URL");
        PageDevice page = getPage(album);
        for (int i = 1; i <= page.getPageTotal(); i++) {
            StringBuilder url = new StringBuilder();
            url.append(chapterUrl);
            url.append(album);
            url.append("&pageNum=");
            url.append(i);
            String responseParam = SendRequestUtil.sendHttpClientGET(url.toString());
            logger.info("章节信息返回结果[{}]", responseParam);
            JSONObject parseObject = JSONObject.parseObject(responseParam);
            JSONObject data = parseObject.getJSONObject("data");
            JSONArray tracks = data.getJSONArray("tracks");
            for (int j = 0; j < tracks.size(); j++) {
                JSONObject track = tracks.getJSONObject(j);
                // 主键
                String uuid = UUIDUtil.getUUID();

                // 名称
                String name = track.getString("title");

                // 路径
                String cUrl = track.getString("url");

                // 喜马拉雅章节id
                Integer trackId = track.getInteger("trackId");

                ChapterInfo chapterInfo = new ChapterInfo();
                chapterInfo.setChapterId(uuid);
                chapterInfo.setChapterName(name);
                chapterInfo.setChapterUrl(cUrl);
                chapterInfo.setHimalayaChId(trackId);
                chapterInfo.setCreateTime(new Date());
                chapterInfo.setChapterSign("0");
                list.add(chapterInfo);
            }
        }
        return list;
    }

    /**
     * 下载有声书
     * @param himalayaChId 书籍id
     * @return
     */
    public static String searchAudio(Integer himalayaChId){
        StringBuilder url = new StringBuilder();
        String audioUrl = PropertiesUtil.getDocking("GET_AUDIO_URL");
        url.append(audioUrl);
        url.append(himalayaChId);
        url.append("&ptype=1");
        String responseParam = SendRequestUtil.sendHttpClientGET(url.toString());
        JSONObject parseObject = JSONObject.parseObject(responseParam);
        JSONObject data = parseObject.getJSONObject("data");
        String src = data.getString("src");
        return src;
    }

    /**
     * 获得指定文件的byte数组
     * @param m4aUrl 声音路径
     * @return
     */
    public static byte[] m4aToByte(String m4aUrl){
        byte[] buffer = null;
        try {

            URL url = new URL(m4aUrl);
            InputStream fis = url.openStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 根据byte数组，生成文件
     * @param bfile byte 数组
     * @param filePath 路径
     * @param fileName 文件名
     */
    public static void getFile(byte[] bfile, String filePath,String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath+"\\"+fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取vip路径的时候可以使用
     * @param trackId 章节id
     * @return
     */
    private static VipUrlDto getVipUrlParam(String trackId){
        VipUrlDto urlDto = new VipUrlDto();
        StringBuilder vipUrl = new StringBuilder();
        String vipAudioBookUrl = PropertiesUtil.getDocking("QUERY_VIP_AUDIO_BOOK_URL");
        vipUrl.append(vipAudioBookUrl);
        vipUrl.append(trackId);
        vipUrl.append("?device=pc");
        String responseParam = SendRequestUtil.sendHttpClientGET(vipUrl.toString());
        //判断过滤
        JSONObject parseObject = JSONObject.parseObject(responseParam);
        if(parseObject.getInteger("ret")==0){
            String domain = parseObject.getString("domain");
            String apiVersion = parseObject.getString("apiVersion");
            String duration = parseObject.getString("duration");
            Integer seed = parseObject.getInteger("seed");
            String ep = parseObject.getString("ep");
            String fileId = parseObject.getString("fileId");
            urlDto.setDomain(domain);
            urlDto.setApiVersion(apiVersion);
            urlDto.setDuration(duration);
            urlDto.setSeed(seed);
            urlDto.setEp(ep);
            urlDto.setFileId(fileId);
        }
        return urlDto;
    }

    /**
     * VIP拼接url
     * @param trackId 章节id
     * @return 有声书路径
     */
    public static String vipAudioUrl(String trackId) {
        //拼接url
        StringBuilder url = new StringBuilder();
        //获取VipDto
        VipUrlDto vipUrlParam = getVipUrlParam(trackId);
        String pathDec = VipEncryption.pathDec(vipUrlParam.getSeed(), vipUrlParam.getFileId());
        List<String> paramDec = VipEncryption.paramDec(vipUrlParam.getEp());
        url.append(vipUrlParam.getDomain());
        url.append("/download/");
        url.append(vipUrlParam.getApiVersion());
        url.append(pathDec);
        url.append("?buy_key=");
        url.append(paramDec.get(0));
        url.append("&sign=");
        url.append(paramDec.get(1));
        url.append("&token=");
        url.append(paramDec.get(2));
        url.append("&timestamp=");
        url.append(paramDec.get(3));
        url.append("&duration=");
        url.append(vipUrlParam.getDuration());
        return url.toString();
    }
}
